package com.a3dweijing.wetouch2.Activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.a3dweijing.wetouch2.Common.CallBack;
import com.a3dweijing.wetouch2.R;
import com.a3dweijing.wetouch2.Util.EvenBusUtil;
import com.a3dweijing.wetouch2.Util.ProgressDialogHelp;
import com.a3dweijing.wetouch2.network.RetrofitUtil;
import com.a3dweijing.wetouch2.Util.Util;
import com.a3dweijing.wetouch2.View.AutoListview;
import com.a3dweijing.wetouch2.adapter.BuyAdapter;
import com.a3dweijing.wetouch2.base.App;
import com.a3dweijing.wetouch2.base.BaseActivity;
import com.a3dweijing.wetouch2.bean.EvenMsg;
import com.a3dweijing.wetouch2.bean.GoodsInfoBean;
import com.a3dweijing.wetouch2.bean.User;
import com.a3dweijing.wetouch2.bean.UserLocationMsg;
import com.a3dweijing.wetouch2.bean.WEIXINGSign;
import com.a3dweijing.wetouch2.datasave.Singleton;
import com.a3dweijing.wetouch2.wxapi.WXCallback;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.a3dweijing.wetouch2.bean.EvenMsg.WXPAYFAIL;
import static com.a3dweijing.wetouch2.bean.EvenMsg.WXPAYSUCCESS;
import static com.a3dweijing.wetouch2.wxapi.WXPayEntryActivity.BUY;

/**
 * g购买确认页面
 */
public class BuyActivity extends BaseActivity implements View.OnClickListener
{
    
    static final int LOCATIONRESULT = 21;
    
    @BindView(R.id.back)
    ImageView back;
    
    @BindView(R.id.top_text)
    TextView topText;
    
    @BindView(R.id.top_right)
    TextView topRight;
    
    @BindView(R.id.top_all)
    RelativeLayout topAll;
    
    @BindView(R.id.resaut_status_img)
    ImageView resautStatusImg;
    
    @BindView(R.id.resaut_status)
    LinearLayout resautStatus;
    
    @BindView(R.id.dingwei_img)
    ImageView dingweiImg;
    
    @BindView(R.id.use_name)
    TextView useName;
    
    @BindView(R.id.dingwei_tv)
    TextView dingweiTv;
    
    @BindView(R.id.pthoer)
    TextView pthoer;
    
    @BindView(R.id.right)
    ImageView right;
    
    @BindView(R.id.my_address)
    RelativeLayout myAddress;
    
    @BindView(R.id.listview)
    AutoListview listview;
    
    @BindView(R.id.submit)
    Button submit;
    
    @BindView(R.id.tv_all_money)
    TextView tvAllMoney;
    
    @BindView(R.id.tv_liuyan)
    TextView tvLiuyan;
    
    @BindView(R.id.ed_liuyan)
    EditText edLiuyan;
    
    private ArrayList<GoodsInfoBean> items;
    
    private BuyAdapter adapter;
    
    private ProgressDialog dialog;
    
    private BigDecimal allmoney;
    
    private UserLocationMsg.AddressBean bean;
    
    public static int BUYACTIVITYCODE = 162;
    
    private int orderId;
    
    private String remarks;
    
    private String address;
    
    /**
     * 记录是否当前页面在付款
     */
    private boolean isBuyIng = false;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy);
        ButterKnife.bind(this);
        EvenBusUtil.register(this);
        items = (ArrayList<GoodsInfoBean>)getIntent().getSerializableExtra("listview");
        orderId = getIntent().getIntExtra("id", -1);
        remarks = getIntent().getStringExtra("remarks");
        address = getIntent().getStringExtra("address");
        if (items == null || items.size() == 0)
        {
            resautStatus.setVisibility(View.VISIBLE);
        }
        else
        {
            initView();
        }
        setOnClick();
        initDate();
    }
    
    private void initDate()
    {
        String userId = Singleton.getInstance().getUser().getUser_id();
        Observable<Msg> defulweizhi = RetrofitUtil.getInstance().getApiOfPhp().defulweizhi(userId);
        defulweizhi.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<Msg>()
        {
            
            @Override
            public void onSubscribe(Disposable d)
            {
                
            }
            
            @Override
            public void onNext(Msg msg)
            {
                if (msg != null && msg.isFlag() && msg.address.size() > 0)
                {
                    bean = msg.getAddress().get(0);
                    initView();
                }
            }
            
            @Override
            public void onError(Throwable e)
            {
                
            }
            
            @Override
            public void onComplete()
            {
                
            }
        });
    }
    
    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        EvenBusUtil.unregister(this);
    }
    
    private void setOnClick()
    {
        myAddress.setOnClickListener(this);
        back.setOnClickListener(this);
        submit.setOnClickListener(this);
    }
    
    private void initView()
    {
        topText.setText("确认订单");
        allmoney = new BigDecimal(0);
        for (GoodsInfoBean item : items)
        {
            BigDecimal multiply = Util.multiplication(item.getS_price(), String.valueOf(item.getNumber()));
            allmoney = allmoney.add(multiply);
        }
        tvAllMoney.setText("总计:" + allmoney.toString());
        dialog = ProgressDialogHelp.create(this, "提示", "提交中", false);
        User user = Singleton.getInstance().getUser();
        useName.setText("收货人：");
        if (orderId != -1)
        {
            dingweiTv.setEnabled(false);
            dingweiTv.setText(address);
            edLiuyan.setText(remarks);
            edLiuyan.setEnabled(false);
        }
        pthoer.setText("联系电话:" + user.getUser_telnum());
        initListview();
        
    }
    
    private void initListview()
    {
        adapter = new BuyAdapter<>(this, items, R.layout.buy_item);
        listview.setAdapter(adapter);
        listview.setListViewHeightBasedOnChildren();
    }
    
    public static void startActivity(Activity context, ArrayList<GoodsInfoBean> goodsInfoBeans)
    {
        if (Util.isFastClick())
        {
            Intent intent = new Intent();
            intent.putExtra("listview", goodsInfoBeans);
            intent.setClass(context, BuyActivity.class);
            context.startActivityForResult(intent, BUYACTIVITYCODE);
        }
    }
    
    /**
     * 订单购买
     *
     * @param context
     * @param goodsInfoBeans
     */
    public static void startActivity(Activity context, ArrayList<GoodsInfoBean> goodsInfoBeans, int orderId,
        String remarks, String address)
    {
        if (Util.isFastClick())
        {
            Intent intent = new Intent();
            intent.putExtra("listview", goodsInfoBeans);
            intent.putExtra("orderid", orderId);
            intent.putExtra("remarks", remarks);
            intent.putExtra("address", address);
            intent.setClass(context, BuyActivity.class);
            context.startActivityForResult(intent, BUYACTIVITYCODE);
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LOCATIONRESULT && resultCode == LOCATIONRESULT && data != null)
        {
            bean = (UserLocationMsg.AddressBean)data.getSerializableExtra("addressbean");
            if (bean != null)
            {
                useName.setText("收货人：" + bean.getConsignee());
                dingweiTv.setText("收货地址:" + bean.getAddress_name());
                pthoer.setText("联系电话:" + bean.getConsignee_tel());
            }
        }
    }
    
    @Override
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.my_address:
                LocationListActivity.startActivityForResult(BuyActivity.this, LOCATIONRESULT);
                break;
            case R.id.back:
                finish();
                break;
            case R.id.submit:
                submit();
                break;
        }
    }
    
    private void submit()
    {
        dialog.show();
        String localIpAddress = Util.getLocalIpAddress(this);
        if (localIpAddress == null)
        {
            dialog.dismiss();
            Toast.makeText(this, "当前ip获取失败", Toast.LENGTH_SHORT).show();
            return;
        }
        if (orderId == -1)
            newOrderBuy(localIpAddress);
        else
            orderBuy(localIpAddress);
    }
    
    private void orderBuy(String localIpAddress)
    {
        Call<JsonObject> call = RetrofitUtil.getInstance().getApiOfPhp().buysnge(orderId, localIpAddress);
        calls.add(call);
        call.enqueue(new WXCallback(this, BUY, new CallBack()
        {
            @Override
            public void doNext(int what, Object obj)
            {
                dialog.dismiss();
                if (what != 0)
                    Toast.makeText(BuyActivity.this, "数据获取失败，请重新尝试", Toast.LENGTH_SHORT).show();
                else
                    isBuyIng = true;
            }
        }));
    }
    
    private void newOrderBuy(String localIpAddress)
    {
        if (bean == null)
        {
            dialog.dismiss();
            Toast.makeText(this, "请填写一个有效地址", Toast.LENGTH_SHORT).show();
            return;
        }
        JSONObject obj = new JSONObject();
        try
        {
            obj.put("localIp", localIpAddress);
            obj.put("order_total", allmoney);
            obj.put("remarks", tvLiuyan.getText().toString());
            obj.put("address_id", bean.getAddress_id());
            JSONArray array = new JSONArray();
            obj.put("goods", array);
            for (GoodsInfoBean item : items)
            {
                JSONObject obj1 = new JSONObject();
                obj1.put("goods_id", item.getS_goods_id());
                obj1.put("goods_number", item.getNumber());
                array.put(obj1);
            }
        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        String content = obj.toString();
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), content);
        Call<JsonObject> call = RetrofitUtil.getInstance().getApiOfPhp().buysnge(body);
        calls.add(call);
        call.enqueue(new WXCallback(this, BUY, new CallBack()
        {
            @Override
            public void doNext(int what, Object obj)
            {
                dialog.dismiss();
                if (what != 0)
                    Toast.makeText(BuyActivity.this, "数据获取失败，请重新尝试", Toast.LENGTH_SHORT).show();
                else
                    isBuyIng = true;
            }
        }));
    }
    
    @Subscribe(threadMode = ThreadMode.MAIN) // 在ui线程执行
    public void onDataSynEvent(EvenMsg evenMsg)
    {
        if (!isBuyIng)
            return;
        else
            isBuyIng = false;
        switch (evenMsg.getWhat())
        {
            case WXPAYSUCCESS:
                Toast.makeText(this, "支付成功", Toast.LENGTH_SHORT).show();
                BuyActivity.this.setResult(RESULT_OK);
                finish();
                break;
            case WXPAYFAIL:
                Toast.makeText(this, "支付失败", Toast.LENGTH_SHORT).show();
                break;
        }
    }
    
    public class Msg
    {
        
        /**
         * flag : true message : 查询成功 address :
         * [{"address_id":7,"address_name":"海南省三沙市西沙群岛测试","consignee":"测试","consignee_tel":"15102892664","user_id":91710036,"add_time":1522292324,"address_state":2}]
         */
        
        private boolean flag;
        
        private String message;
        
        private List<UserLocationMsg.AddressBean> address;
        
        public List<UserLocationMsg.AddressBean> getAddress()
        {
            return address;
        }
        
        public void setAddress(List<UserLocationMsg.AddressBean> address)
        {
            this.address = address;
        }
        
        public boolean isFlag()
        {
            return flag;
        }
        
        public void setFlag(boolean flag)
        {
            this.flag = flag;
        }
        
        public String getMessage()
        {
            return message;
        }
        
        public void setMessage(String message)
        {
            this.message = message;
        }
        
    }
}
